<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\AliPayAppController;
use App\Http\Controllers\AliPayController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\PlaceController;
use App\Http\Controllers\SmsController;
use App\Http\Controllers\WechatController;
use App\Models\BrowseJob;
use App\Models\CollArea;
use App\Models\CollPosition;
use App\Models\CompanyBasic;
use App\Models\CompanyJob;
use App\Models\CompanyUser;
use App\Models\Interview;
use App\Models\PersonalUser;
use App\Models\Resume;
use App\Models\ResumeSend;
use App\Models\WebConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Validator, DB;

class CompanyController extends CommonController
{
    /**
     * 所有职位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobs(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;
        $type = $request->type;

//        return response()->json(['status' => 0, 'msg' => $request->lat]);

        $company_job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            //获取字段
            ->select(
                't1.id', 't1.job_title', 't1.job_category1', 't1.location1', 't1.address', 't1.salary', 't1.description', 't1.welfare', 't1.updatetime', 't1.ip_id',
                't2.company_name', 't2.logo'
            )
            ->where('job_status', 1)
            //本公司招聘除外
            ->where(function ($query) use ($request) {
                $user = auth()->guard('company')->user();
                if ($user && $user->uid > 0) {
                    $query->where('t1.uid', '!=', $user->uid);
                }
            })
            //薪资
            ->where(function ($query) use ($request) {
                if (!empty($request->salary)) {
                    $salarys = WebConfig::getConfig('salary');

                    if ($salarys) {
                        $salarys1 = explode(',', $salarys);
                        foreach ($salarys1 as $v111) {
                            $arr = explode(':', $v111);
                            if ($arr[0] != $request->salary) {
                                continue;
                            }
                            $salarysStr = $arr[1];
                            $salarysArr = explode('-', $salarysStr);
                            if ($salarysArr) {
                                $minSalary = $salarysArr[0];
                                $maxSalary = $salarysArr[1];

                                if ($maxSalary > $minSalary) {
                                    $query->where('t1.salary', '>=', $minSalary)
                                        ->where('t1.salary', '<', $maxSalary);
                                }
                            }

                        }
                    }
                }
            })
            //工作地点
            ->where(function ($query) use ($request) {
                $location1 = $request->input('district');

                if ($location1 > 0) {
                    $query->where('t1.location1', '=', $location1);
                }
            })
            //所属行业
            ->where(function ($query) use ($request) {
                $job_category1 = $request->input('jobsort');

                if ($job_category1 > 0) {
                    $query->where('t1.job_category1', '=', $job_category1);
                }
            })
            //关键字
            ->where(function ($query) use ($request) {
                if (!empty($request->keyword)) {
                    $query->where('t1.job_title', 'like', '%' . $request->keyword . '%')
                        ->orWhere('t2.company_name', 'like', '%' . $request->keyword . '%');
                }
            })
            ->orderBy('id', 'desc')
            ->get()->toArray();

        $lat = $request->lat;
        $lng = $request->lng;

        if (count($company_job) > 0) {
            $farNear = WebConfig::getConfig('far_nearby');

            foreach ($company_job as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);

                if ($type == 2 && $lat > 0 && $lng > 0 && $v->ip_id > 0) {
                    $latlng = DB::table('latlng_info')->where('id', $v->ip_id)->value('auto_navi');
                    $latlngArr = explode(',', $latlng);

                    $v->distance = $this->getDistance($lat, $lng, $latlngArr[1], $latlngArr[0]);
                    if ($v->distance > $farNear) {
                        unset($company_job[$k]);
                        continue;
                    }
                    $v->distance = round($v->distance, 2);
                } else {
                    $v->distance = 0;
                }

                $v->is_new = 0;
            }

            $company_job_arr = $this->object_to_array($company_job);

            if ($type == 2 && $lat > 0 && $lng > 0) {
                $distances = array_column($company_job_arr, 'distance');
                array_multisort($distances, SORT_ASC, $company_job_arr);
            }

            $company_job_arr = array_slice($company_job_arr, $start, $totalList);
        } else {
            $company_job_arr = [];
        }

        return response()->json(['status' => 1, 'data' => $company_job_arr]);
    }

    public function getNewNum(Request $request)
    {
        $uid = $request->uid;
        $today = date('Y-m-d', time());

        $members = DB::table('personal_users as t1')
            ->join('resume as t2', 't1.uid', '=', 't2.uid')
            ->where('t2.resume_status', '>=', 2)
            ->whereDate('t2.updatetime', $today)
            ->pluck('t1.uid')
            ->toArray();

        $num = count($members);
        $broswerWorkers = DB::table('browse_worker')
//            ->whereDate('updated_at', $today)
            ->where('company_uid', $uid)
            ->pluck('personal_uid')
            ->toArray();
        if ($broswerWorkers) {
            $commonArr = array_intersect($members, $broswerWorkers);
            $num = count($members) - count($commonArr);
        }

        return response()->json(['status' => 1, 'data' => $num]);
    }

    public function jobsc(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;

        $members = DB::table('personal_users as t1')
            ->join('resume as t2', 't1.uid', '=', 't2.uid')
            //获取字段
            ->select(
                't2.uid', 't2.avatar', 't2.realname', 't2.sex', 't2.birthday', 't2.work_year', 't2.introduction', 't2.jobsort1', 't2.regtime', 't2.updatetime', 't2.jobarea1', 't2.ip_id'
//                't2.company_name', 't2.logo'
            )
            ->where('t2.resume_status', '>=', 2)
            //本公司招聘除外
//            ->where(function ($query) use ($request) {
//                $user = auth()->guard('company')->user();
//                if ($user && $user->uid > 0) {
//                    $query->where('t1.uid', '!=', $user->uid);
//                }
//            })
            ->where(function ($query) use ($request) {
                if ($request->jobsort > 0) {
                    $query->where('t2.jobsort1', $request->jobsort);
                }
            })
//            //工作地点
            ->where(function ($query) use ($request) {
                if ($request->district > 0) {
                    $query->where('t2.jobarea1', $request->district);
                }
            })
            //性别要求
            ->where(function ($query) use ($request) {
                if (in_array($request->sex, [1, 2])) $query->where('t2.sex', $request->sex);
            })
            //工作经验 当前所选工作经验以上
            ->where(function ($query) use ($request) {
                if (!empty($request->work_year)) {
                    $workYears = WebConfig::getConfig('work_year');
                    if ($workYears) {
                        $workYears1 = explode(',', $workYears);
                        foreach ($workYears1 as $v111) {
                            $arr = explode(':', $v111);
                            if ($arr[0] != $request->work_year) {
                                continue;
                            }
                            $yearStr = $arr[1];
                            $yearArr = explode('-', $yearStr);
                            if ($yearArr) {
                                $minYear = $yearArr[0];
                                $maxYear = $yearArr[1];
                                if ($maxYear > $minYear) {
                                    $query->where('t2.work_year', '>=', $minYear)
                                        ->where('t2.work_year', '<', $maxYear);
                                }
                            }

                        }
                    }
                }
            })
            //关键字
            ->where(function ($query) use ($request) {
                if (!empty($request->keyword)) {
                    $ids1 = CollPosition::where('name', 'like', '%' . $request->keyword . '%')->select('cid')->get()->toArray();
                    $ids = [];
                    if ($ids1) {
                        foreach ($ids1 as $v) {
                            $ids[] = $v['cid'];
                        }
                    }

                    $query->whereIn('t2.jobsort1', $ids);
                }
            })
            ->orderBy('uid', 'desc')
            ->skip($start)->take($totalList)
            ->get();

        if (count($members) > 0) {
            foreach ($members as $k => $v) {
                $v->age = date('Y', time()) - date('Y', strtotime($v->birthday));

                if ($v->sex == 1) {
                    $v->sex = '男';
                } elseif ($v->sex == 2) {
                    $v->sex = '女';
                }

                $v->jobarea = CollArea::getAreaName($v->jobarea1);

                if (trim($v->jobarea) == '') {
                    $v->jobarea = "地区不限";
                }

                $v->jobsort = CollPosition::where('cid', $v->jobsort1)->value('name');

                $v->is_new = 0;
                $updateTime = strtotime($v->updatetime) - strtotime('today');
                if ($updateTime < 0) {
                    continue;
                }
                //今天
                $uid = $request->uid;
                $broWorker = DB::table('browse_worker')->where('company_uid', $uid)->where('personal_uid', $v->uid)->first();
                if (!$broWorker) {
                    $v->is_new = 1;
                }
            }
            $members_arr = $this->object_to_array($members);

        } else {
            $members_arr = [];
        }

        return response()->json(['status' => 1, 'data' => $members_arr]);
    }

    /**
     * 未发布的项目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobs1(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;

        $uid = $request->uid;

        $company_job = DB::table('company_job')
            //获取字段
            ->select('id', 'job_title', 'job_status', 'addtime', 'updatetime')
            ->where('uid', $uid)
            ->where(function ($query) use ($request) {
                $jobStatus = $request->job_status;
                if (in_array($jobStatus, [-1, 0, 1])) {
                    $query->where('job_status', $jobStatus);
                } else {
                    $query->whereIn('job_status', [-1, 0, 1]);
                }
            })
            ->orderBy('id', 'desc')
            ->skip($start)->take($totalList)->get();

        return response()->json(['status' => 1, 'data' => $company_job]);
    }

    /**
     * 工程详情
     * @param $jobid
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobInfo($jobid)
    {
        $jobinfo = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_users as t3', 't2.uid', '=', 't3.uid')
            //获取字段
            ->select(
                't1.id', 't1.com_id', 't1.uid', 't1.job_title', 't1.job_category1', 't1.job_status', 't1.location1', 't1.address', 't1.ip_id', 't1.salary', 't1.total', 't1.description', 't1.welfare', 't1.begin_date', 't1.updatetime',
                't2.company_name', 't2.logo', 't2.coordinate_address',
                't3.mobile'
            )
            ->where('t1.id', $jobid)
            ->first();

        $number = DB::table('company_job')
            ->where('uid', $jobinfo->uid)->where('job_status', 1)
            ->count();

        $jobinfo->num = $number;

        if ($jobinfo->salary == 0) {
            $jobinfo->salary = '面议';
        }
        //返回招聘工作地点
        $location = '';
        if ($jobinfo->location1) {
            $districtInfo = CollArea::select('name', 'grade', 'pid')->where('cid', $jobinfo->location1)->first();
            $pdistrictInfo = CollArea::select('name', 'grade', 'pid')->where('grade', $districtInfo->grade - 1)->where('cid', $districtInfo->pid)->first();
            $location = $pdistrictInfo->name . $districtInfo->name;
            if ($pdistrictInfo->grade == 2) {
                $ppname = CollArea::where('grade', $pdistrictInfo->grade - 1)->where('cid', $pdistrictInfo->pid)->value('name');
                $location = $ppname . $location;
            }
        }

        $jobinfo->location = $location . $jobinfo->address;

        if (trim($jobinfo->location) == '') {
            $jobinfo->location = "地区不限";
        }

        $latlngInfo = DB::table('latlng_info')->where('id', $jobinfo->ip_id)->first();
        $maps = [];
        if ($latlngInfo) {
            $maps[] = explode(',', $latlngInfo->auto_navi);
            $maps[] = explode(',', $latlngInfo->tencent);
            $maps[] = explode(',', $latlngInfo->baidu);
        }

        $jobinfo->ip_maps = $maps;

        return response()->json(['status' => 1, 'data' => $jobinfo]);
    }

    /**
     * 公司详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $uid = $request->uid;
        $cInfo = DB::table('company_users as u')
            ->join('company_basic as b', 'u.uid', '=', 'b.uid')
            ->select(
                'b.uid', 'b.logo', 'b.status', 'b.employee_num', 'b.region', 'b.address', 'b.introduction', 'b.id1', 'b.ID2', 'b.license', 'u.mobile',
                'u.company_name', 'u.password2', 'u.wechatid'
            )->where('u.uid', $uid)
            ->first();

        $cInfo->regionStr = CollArea::getAreaAddressThree($cInfo->region);

        $num = DB::table('browse_worker')->where('company_uid', $uid)->count();
        $cInfo->broswer_num = $num;

        return response()->json(['status' => 1, 'data' => $cInfo]);
    }

    /**
     * 公司详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getComInfo(Request $request)
    {
        $id = $request->id;
        $cInfo = CompanyBasic::where('id', $id)->first();

        $location = '';
        if ($cInfo->region) {
            $districtInfo = CollArea::select('name', 'grade', 'pid')->where('cid', $cInfo->region)->first();
            $pdistrictInfo = CollArea::select('name', 'grade', 'pid')->where('grade', $districtInfo->grade - 1)->where('cid', $districtInfo->pid)->first();
            $location = $pdistrictInfo->name . $districtInfo->name;
            if ($pdistrictInfo->grade == 2) {
                $ppname = CollArea::where('grade', $pdistrictInfo->grade - 1)->where('cid', $pdistrictInfo->pid)->value('name');
                $location = $ppname . $location;
            }
        }

        $cInfo->location = $location . $cInfo->address;

        if (trim($cInfo->location) == '') {
            $cInfo->location = "地区不限";
        }

        return response()->json(['status' => 1, 'data' => $cInfo]);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd(Request $request)
    {
        $input = $request->only(['mobile', 'code', 'password']);
        if (!$input['mobile'] || !$input['code'] || !$input['password']) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uinfo = CompanyUser::where('mobile', $input['mobile'])->select('uid', 'password')->first();
        if (!$uinfo) {
            return response()->json(['status' => 0, 'msg' => '该账户不存在！']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($input['mobile'], $input['code']);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        if (Hash::check($input['password'], $uinfo->password)) {
            return response()->json(['status' => 0, 'msg' => '新密码与原密码一致！']);
        }

        $npwd = Hash::make($input['password']);

        $result = CompanyUser::where('uid', $uinfo->uid)->update(['password' => $npwd]);
        if ($result) {
            return response()->json(['status' => 1, 'msg' => '重置成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '重置失败！']);
        }
    }

    /**
     * 用户注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $input = $request->only(['mobile', 'code', 'password']);

        $rules = [
            'code' => 'required',
            'mobile' => 'required|size:11',
            'password' => 'required|min:6'
        ];
        $messages = [
            'mobile.size' => '手机号码为11位',
            'code.required' => '短信验证码必填',
            'password.required' => '登录密码必填',
            'password.min' => '登录密码不能少于6位数'
        ];

        $validate = Validator::make($input, $rules, $messages);
        if ($error = $validate->errors()->first()) {
            return response()->json(['status' => 0, 'msg' => $error]);
        }

        $user = CompanyUser::where('mobile', $input['mobile'])->first();
        if ($user) {
            return response()->json(['status' => 0, 'msg' => '该手机号码已注册']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($input['mobile'], $input['code']);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        DB::beginTransaction();
        try {
            $udata = [
                'mobile' => $input['mobile'],
                'password' => Hash::make($input['password']),
//                'contacts' => $input['contact'],
//                'company_name' => $input['company_name'],
//                'email' => $input['email'],
                'wechatid' => 0,
                'regtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time()),
                'last_login_time' => date('Y-m-d H:i:s', time()),
                'regip' => $request->ip(),
                'last_login_ip' => $request->ip()
            ];

            $res1 = CompanyUser::create($udata);

            //注册并登录
            CompanyBasic::create([
                'uid' => $res1->uid,
//                'company_name' => $input['company_name'],
//                'contacts' => $input['contact'],
//                'mobile' => $input['company_mobile'],
//                'email' => $input['email'],
                'addtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time())
            ]);

            DB::table('users')->insert(['uid' => $res1->uid, 'type' => 2]);

            DB::commit();
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return response()->json(['status' => 0, 'msg' => '注册失败']);
        }

        return response()->json(['status' => 1, 'msg' => '注册成功', 'data' => $udata]);
    }

    /**
     * 个人详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $info = DB::table('personal_users as p')
            ->join('resume as r', 'p.uid', '=', 'r.uid')
            ->select(
                'p.uid', 'p.mobile',
                'r.realname', 'r.sex', 'r.avatar', 'r.resume_status', 'r.birthday', 'r.work_year', 'r.introduction', 'r.jobarea1', 'r.jobsort1', 'r.expectedsalary', 'r.id1', 'r.ID2', 'r.regtime'
            )->where('p.uid', $request->person_uid)
            ->first();
        if ($info->jobarea1) {
            $jobarea1 = $info->jobarea1;
            $info->jobarea1 = CollArea::getAreaAddress($jobarea1);
            $info->jobarea11 = CollArea::getAreaAddressThree($jobarea1);
        }
        if ($info->jobsort1) {
            $info->jobsort1 = CollPosition:: getPosName($info->jobsort1);
        }

        if ($info->birthday) {
            $info->age = date('Y') - date('Y', strtotime($info->birthday));
        }
        return response()->json(['status' => 1, 'data' => $info]);
    }

    /**
     * 发布工作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobPublish(Request $request)
    {
        $uid = $request->uid;
        $companyBasic = CompanyBasic::where('uid', $uid)->select('id', 'status')->first();
        $status = $companyBasic->status;

        if ($status == 0) {
            return response()->json(['status' => 10, 'msg' => '请先完成公司信息！']);
        } elseif ($status == 1) {
            return response()->json(['status' => 11, 'msg' => '请先完成实名认证！']);
        } elseif ($status == 2) {
            return response()->json(['status' => 12, 'msg' => '等待后台认证审核！']);
        }

        $input = $request->only(['job_title', 'gender', 'begin_date', 'job_category1', 'location1', 'salary', 'days', 'age_below', 'age_above', 'description', 'address']);
        $rules = [
            'job_title' => 'required',
            'gender' => 'required',
//            'is_appoint' => 'required',
            'begin_date' => 'required',
            'job_category1' => 'required',
            'location1' => 'required',
            'address' => 'required',
            'salary' => 'required',
            'days' => 'required',
            'age_below' => 'required|integer|min:16',
            'age_above' => 'required|integer|max:60'
        ];
        $messages = [
            'job_title.required' => '项目名称必填',
            'gender.required' => '性别必选',
//            'is_appoint.required' => '是否预约必选',
            'begin_date.required' => '开工日期必选',
            'job_category1.required' => '工种必选',
            'location1.required' => '工作地区必选',
            'address.required' => '详细地址必填',
            'salary.required' => '工资必填',
            'days.required' => '工作天数必填',
            'age_below.required' => '最小年龄必填',
            'age_below.integer' => '最小年龄必为整数',
            'age_below.min' => '最小年龄不能小于16岁',
            'age_above.required' => '最大年龄必填',
            'age_above.integer' => '最大年龄必为整数',
            'age_above.max' => '最大年龄不能超过60岁'
        ];

        $validate = Validator::make($input, $rules, $messages);
        if ($error = $validate->errors()->first()) {
            return response()->json(['status' => 0, 'msg' => $error]);
        }

        $times = 7 * 24 * 60 * 60;
        if (strtotime($input['begin_date']) - time() > $times) {
            return response()->json(['status' => 0, 'msg' => '距开工日期超过7天不可发布！']);
        }

        $input['addtime'] = date('Y-m-d H:i:s', time());
        $input['updatetime'] = date('Y-m-d H:i:s', time());
        $input['uid'] = $request->uid;

        $input['com_id'] = $companyBasic->id;
        $input['job_status'] = 0;

        $location1 = CollArea::getAreaAddress($input['location1']);
        $address = $location1 . $input['address'];
        $place = new PlaceController();
        $id = $place->getLocation($address);

        if (!$id) {
            return response()->json(['status' => 0, 'msg' => '地址解析错误！']);
        }

        $input['ip_id'] = $id;

        $input['order_num'] = substr(md5(uniqid()), 1);
        $input['total'] = $input['salary'] * $input['days'];

        DB::beginTransaction();
        try {
            CompanyJob::create($input);
            DB::commit();
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return response()->json(['status' => 0, 'msg' => '注册失败']);
        }

        return response()->json(['status' => 1, 'msg' => '发布成功']);
    }

    /**
     * 更新状态
     * @param $uid
     */
    public function toStatus($uid)
    {
        $info = DB::table('company_users as u')
            ->join('company_basic as b', 'u.uid', '=', 'b.uid')
            ->select(
                'b.logo', 'b.employee_num', 'b.region', 'b.status', 'b.address', 'b.introduction',
                'u.company_name'
            )->where('u.uid', $uid)
            ->first();

        if ($info->logo && $info->employee_num && $info->region && $info->address && $info->introduction && $info->company_name) {
            if (in_array($info->status, [0])) {
                CompanyBasic::where('uid', $uid)->update(['status' => 1]);
            }
        }
    }

    /**
     * 更新logo
     * @return array
     */
    public function changeLogo(Request $request)
    {
        $logo = $request->logo;
        CompanyBasic::where('uid', $request->uid)->update(['logo' => $logo]);
        self::toStatus($request->uid);
        return response()->json(['status' => 1, 'msg' => '更新成功']);
    }

    /**
     * 更新公司名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeCompanyName(Request $request)
    {
        $companyName = trim($request->company_name);
        if (!$companyName) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $cinfo = CompanyBasic::where('uid', $uid)->select('company_name')->first();

        if ($cinfo->company_name == $companyName) {
            return response()->json(['status' => 0, 'msg' => '公司名称和原名称一致！']);
        }

        $res = CompanyBasic::where('uid', $request->uid)->update(['company_name' => $companyName]);
        if ($res) {
            self::toStatus($request->uid);
            CompanyUser::where('uid', $request->uid)->update(['company_name' => $companyName]);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新公司规模
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeEmployeeNum(Request $request)
    {
        $employeeNum = trim($request->employee_num);
        if (!$employeeNum) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $cinfo = CompanyBasic::where('uid', $uid)->select('employee_num')->first();

        if ($cinfo->employee_num == $employeeNum) {
            return response()->json(['status' => 0, 'msg' => '公司人数和原人数一致！']);
        }

        $res = CompanyBasic::where('uid', $request->uid)->update(['employee_num' => $employeeNum]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新企业所在地
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeRegion(Request $request)
    {
        $region = trim($request->region);
        if (!$region) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $cinfo = CompanyBasic::where('uid', $uid)->select('region')->first();

        if ($cinfo->region == $region) {
            return response()->json(['status' => 0, 'msg' => '所在地区和原地区一致！']);
        }

        $res = CompanyBasic::where('uid', $request->uid)->update(['region' => $region]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新详细地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeCompanyAddress(Request $request)
    {
        $companyAddress = trim($request->company_address);
        if (!$companyAddress) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $cinfo = CompanyBasic::where('uid', $uid)->select('address')->first();

        if ($cinfo->address == $companyAddress) {
            return response()->json(['status' => 0, 'msg' => '详细地址和原地址一致！']);
        }

        $res = CompanyBasic::where('uid', $request->uid)->update(['address' => $companyAddress]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新联系方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeCompanyMobile(Request $request)
    {
        $mobile = trim($request->mobile);
        if (!$mobile) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }
        $uid = $request->uid;
        $cMobile = CompanyUser::where('uid', $uid)->value('mobile');

        if ($cMobile == $mobile) {
            return response()->json(['status' => 0, 'msg' => '联系方式未改变！']);
        }
        $company = CompanyUser::where('mobile', $mobile)->where('uid', '!=', $uid)->select('uid')->get();
        if (count($company) > 0) {
            return response()->json(['status' => 0, 'msg' => '该联系方式已存在！']);
        }

        $res = CompanyUser::where('uid', $uid)->update(['mobile' => $mobile]);
        if ($res) {
            CompanyBasic::where('uid', $uid)->update(['mobile' => $mobile]);
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 公司简介
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeCompanyIntroduce(Request $request)
    {
        $companyIntroduce = trim($request->company_introduce);
        if (!$companyIntroduce) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $res = CompanyBasic::where('uid', $request->uid)->update(['introduction' => $companyIntroduce]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function changeid1(Request $request)
    {
        $id1 = trim($request->path);
        if (!$id1) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = CompanyBasic::where('uid', $uid)->update(['id1' => $id1]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function changeID2(Request $request)
    {
        $id1 = trim($request->path);
        if (!$id1) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = CompanyBasic::where('uid', $uid)->update(['ID2' => $id1]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function changeLicense(Request $request)
    {
        $license = trim($request->path);
        if (!$license) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = CompanyBasic::where('uid', $uid)->update(['license' => $license]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function authReply(Request $request)
    {
        $uid = $request->uid;
        $info = DB::table('company_users as u')
            ->join('company_basic as b', 'u.uid', '=', 'b.uid')
            ->select(
                'b.logo', 'b.id1', 'b.ID2', 'b.status', 'b.license', 'b.introduction',
                'u.company_name'
            )->where('u.uid', $uid)
            ->first();

        if (!in_array($info->status, [-1, 1])) {
            return response()->json(['status' => 0, 'msg' => '暂时不可申请！']);
        }

        if (!($info->id1 && $info->ID2)) {
            return response()->json(['status' => 0, 'msg' => '请先上传身份证！']);
        }

        if (!$info->license) {
            return response()->json(['status' => 0, 'msg' => '请先上传营业执照！']);
        }

        CompanyBasic::where('uid', $uid)->update(['status' => 2]);
        return response()->json(['status' => 1, 'msg' => '申请成功']);
    }

    /**
     * 邀请列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function interviews(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $interview = DB::table('interview as t1')
            ->join('resume as t2', 't1.personal_uid', '=', 't2.uid')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->select(
                't1.status',
                't3.id', 't3.job_title',
                't2.uid', 't2.realname', 't2.avatar', 't2.sex', 't2.birthday', 't2.work_year', 't2.jobsort1'
            )
            ->where('t1.company_uid', $uid)
            ->where('t1.status', '!=', 4)
            ->orderBy('updated_at', 'desc')
            ->skip($start)->take(self::$totalList)
            ->get();

        if ($interview) {
            foreach ($interview as $k => $v) {
                $v->age = date('Y', time()) - date('Y', strtotime($v->birthday));

                switch ($v->sex) {
                    case 1:
                        $v->sex = '男';
                        break;
                    case 2:
                        $v->sex = '女';
                        break;
                }

                $v->jobsort = CollPosition::getPosName($v->jobsort1);

                $v->interview_status = $v->status;
            }
        }

        return response()->json(['status' => 1, 'data' => $interview]);
    }

    /**
     * 企业的所有工作订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobList(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $status = $request->status;
        $company_jobs = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            //获取字段
            ->select(
                't1.id', 't1.job_title', 't1.job_category1', 't1.location1', 't1.address', 't1.salary', 't1.total', 't1.description', 't1.welfare', 't1.updatetime', 't1.job_status',
                't2.company_name', 't2.logo'
            )
            ->where(function ($query) use ($status) {
                if ($status >= 10) {
                    $query->where('t1.job_status', $status);
                } else {
                    $query->where('t1.job_status', '>=', 10);
                }
            })
            ->where('t1.uid', $uid)
            ->orderBy('id', 'desc')
            ->skip($start)->take(self::$totalList)
            ->get();

        if (count($company_jobs) > 0) {
            foreach ($company_jobs as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);
            }
        }

        return response()->json(['status' => 1, 'data' => $company_jobs]);
    }

    /**
     * 设置状态
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function status(Request $request)
    {
        $uid = $request->uid;
        $id = $request->jobId;
        $companyJob = CompanyJob::select('id', 'job_status', 'job_title', 'order_num', 'salary', 'days', 'total')->where('uid', $uid)->where('id', $id)->first();
        if (!$companyJob) {
            return response()->json(['status' => 0, 'msg' => "参数缺失或错误！"]);
        }

        $ostatus = $companyJob->job_status;
        switch ($ostatus) {
            case -2 | 30;
                return response()->json(['status' => 0, 'msg' => "该项目不可操作！"]);
                break;
            case -1;
                $allow = array(-2, 0);
                break;
            case 0;
                $allow = array(-2, -1);
                break;
            case 1;
                $allow = array(10);
                break;
            case 10;
                $allow = array(20);
                break;
            case 20;
                $allow = array(30);
                break;
        }

        if (!in_array($request->status, $allow)) {
            return response()->json(['status' => 0, 'msg' => "操作失败！"]);
        }

        if ($request->status == 20) {

//            $salary = $request->salary;
//            if (!$salary || $salary <= 0) {
//                return response()->json(['status' => 404, 'msg' => "薪资额度非法！"]);
//            }
//
//            if ($salary < $companyJob->salary_above) {
//                return response()->json(['status' => 404, 'msg' => "薪资额度不能低于最低额度！"]);
//            }
            $salary = $companyJob->salary;
            $days = $companyJob->days;

            if ($salary <= 0) {
                return response()->json(['status' => 0, 'msg' => "每日薪资缺失！"]);
            }
            if ($days <= 0) {
                return response()->json(['status' => 0, 'msg' => "工作天数缺失！"]);
            }
            $num1 = CompanyJob::find($id)->job_resume_send();
            $num2 = Interview::where('company_uid', $uid)
                ->where('job_id', $id)
                ->where('status', 2)
                ->count();
            $num = $num1 + $num2;
            if ($num <= 0) {
                return response()->json(['status' => 0, 'msg' => "尚未招募到人员，不可支付！"]);
            }
            $total = round($salary * $num * $days, 2);

            if ($companyJob->salary != $salary || $companyJob->total != $total) {
                $res = CompanyJob::where('id', $id)->update(['salary' => $salary, 'total' => $total]);
                if (!$res) {
                    return response()->json(['status' => 0, 'msg' => "薪资总额更新失败！"]);
                }
            }

            //微信支付
            $paytype = $request->paytype;

            switch ($paytype) {
                case 1:
                    $ip = $request->getClientIp();

                    $data = [
                        "body" => $companyJob->job_title,
                        "out_trade_no" => $companyJob->order_num,
                        //                "out_trade_no" => time(),
                        "client_ip" => $ip,
                        "money" => $total,
//                        "money" => 1,
                    ];

                    $type = $request->type;
                    if ($type == 2) {
                        $data["openid"] = $request->openid;
                    }

                    $payMent = new PaymentController();
                    $res = $payMent->wx_pay($data, $type, 'job');

                    if ($res['status'] == 0) {
                        return response()->json(['status' => 0, 'msg' => $res['msg']]);
                    } else {
                        return response()->json($res);
                    }
                    break;
                case 2:
                    //支付宝支付
                    $data = [
                        "out_trade_no" => $companyJob->order_num,
                        "subject" => $companyJob->job_title,
                        "total_amount" => $total,
//                        "total_amount" => 0.01,
                        "body" => $companyJob->job_title,
                        "timeout_express" => '1m',
                    ];

                    $type = $request->type;
                    if ($type == 3) {
                        $alipay = new AliPayController();
                    } elseif ($type == 4) {
                        $alipay = new AliPayAppController();
                    }

                    $result = $alipay->ali_pay($data, 'job');

                    return $result;
                    break;
                default:
                    return response()->json(['status' => 0, 'msg' => "请选择合法的支付方式！"]);
                    break;
            }
        } else {
            $companyJob->job_status = $request->status;
            $companyJob->xs_status = 0;
            $companyJob->save();

            switch ($request->status) {
                case -2 :
                    $message = '职位删除成功！';
                    break;
                case -1 :
                    $message = '职位屏蔽成功！';
                    break;
                case 0 :
                    $message = '职位申请成功！';
                    break;
                case 10 :
                    $message = '该项目招聘已结束！';
                    break;
                case 20 :
                    $message = '该项目订单已支付！';
                    break;
                case 30 :
                    $message = '该项目已结束！';
                    break;
                default:
                    $message = '未知错误！';
            }
            return response()->json(['status' => 1, 'msg' => $message]);
        }
    }

    /**
     * 发送简历
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resumeSend(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        //简历投递记录
        $sends = DB::table('resume_send as t1')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->join('resume as t2', 't2.uid', '=', 't1.personal_uid')
            ->select(
                't1.status',
                't3.id', 't3.job_title',
                't2.uid', 't2.realname', 't2.avatar', 't2.sex', 't2.birthday', 't2.work_year', 't2.jobsort1'
            )
            ->where('t3.uid', $uid)
            ->where('t1.status', '!=', 4)
            ->orderBy('updated_at', 'desc')
            ->skip($start)->take(self::$totalList)
            ->get();
        //处理数组
        if ($sends) {
            foreach ($sends as $k => $v) {
                $v->age = date('Y', time()) - date('Y', strtotime($v->birthday));

                switch ($v->sex) {
                    case 1:
                        $v->sex = '男';
                        break;
                    case 2:
                        $v->sex = '女';
                        break;
                }

                $v->jobsort = CollPosition::getPosName($v->jobsort1);

            }
        }

        return response()->json(['status' => 1, 'data' => $sends]);
    }

    /**
     * 企业是否收藏某员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isCollectWorker(Request $request)
    {
        $uid = $request->uid;
        $personUid = $request->person_uid;
        $collect = DB::table('collection_worker')->where('uid', $uid)->where('personal_uid', $personUid)->first();
        if ($collect) {
            $isCollect = 1;
        } else {
            $isCollect = 0;
        }

        return response()->json(['status' => 1, 'data' => $isCollect]);
    }

    /**
     * 收藏员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCollectWorker(Request $request)
    {
        $uid = $request->uid;
        $personUid = $request->person_uid;
        $collect = DB::table('collection_worker')->where('uid', $uid)->where('personal_uid', $personUid)->first();
        if ($collect) {
            return response()->json(['status' => 2, 'msg' => '已收藏！']);
        } else {
            $data = [
                'uid' => $uid,
                'personal_uid' => $personUid,
                'regtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time()),
                'status' => 1
            ];
            DB::table('collection_worker')->insert($data);
            return response()->json(['status' => 1, 'msg' => '收藏成功！']);
        }
    }

    /**
     * 取消收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delCollectWorker(Request $request)
    {
        $uid = $request->uid;
        $personUid = $request->person_uid;
        $collect = DB::table('collection_worker')->where('uid', $uid)->where('personal_uid', $personUid)->first();
        if (!$collect) {
            return response()->json(['status' => 2, 'msg' => '未收藏！']);
        } else {
            DB::table('collection_worker')->where('id', $collect->id)->delete();
            return response()->json(['status' => 1, 'msg' => '取消成功！']);
        }
    }

    /**
     * 我收藏的员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function collectWorkers(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;
        $uid = $request->uid;

        $workers = DB::table('collection_worker as t1')
            ->join('resume as t2', 't1.personal_uid', '=', 't2.uid')
            //获取字段
            ->select(
                't2.uid', 't2.avatar', 't2.realname', 't2.sex', 't2.birthday', 't2.work_year', 't2.introduction', 't2.jobsort1', 't2.regtime', 't2.jobarea1'
            )
            ->where('t1.uid', $uid)
            ->orderBy('t1.id', 'desc')
            ->skip($start)->take($totalList)->get();

        if (count($workers) > 0) {
            foreach ($workers as $k => $v) {
                $v->age = date('Y', time()) - date('Y', strtotime($v->birthday));

                if ($v->sex == 1) {
                    $v->sex = '男';
                } elseif ($v->sex == 2) {
                    $v->sex = '女';
                }

                $v->jobarea = CollArea::getAreaName($v->jobarea1);

                if (trim($v->jobarea) == '') {
                    $v->jobarea = "地区不限";
                }

                $v->jobsort = CollPosition::where('cid', $v->jobsort1)->value('name');
            }
        }

        return response()->json(['status' => 1, 'data' => $workers]);
    }


    /**
     * 添加员工浏览记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addBrowseWorker(Request $request)
    {
        $personalUid = $request->personal_uid;
        $uid = $request->uid;
        $browseWorker = DB::table('browse_worker')->where("company_uid", $uid)->where("personal_uid", $personalUid)->first();
        if (!$browseWorker) {
            $addBrowseWorder = [
                "company_uid" => $uid,
                "personal_uid" => $personalUid,
                "created_at" => date('Y-m-d H:i:s', time()),
                "updated_at" => date('Y-m-d H:i:s', time())
            ];
            $res = DB::table('browse_worker')->insert($addBrowseWorder);

            if ($res) {
                return response()->json(['status' => 1, 'msg' => '添加成功！']);
            } else {
                return response()->json(['status' => 0, 'msg' => '添加失败！']);
            }
        } else {
            return response()->json(['status' => 2, 'msg' => '已添加记录！']);
        }
    }

    /**
     * 浏览记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function browseWorkers(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;

        $uid = $request->uid;

        $workers = DB::table('browse_worker as t1')
            ->join('resume as t2', 't1.personal_uid', '=', 't2.uid')
            //获取字段
            ->select(
                't2.uid', 't2.avatar', 't2.realname', 't2.sex', 't2.birthday', 't2.work_year', 't2.introduction', 't2.jobsort1', 't2.regtime', 't2.jobarea1'
            )
            ->where('t1.company_uid', $uid)
            ->orderBy('t1.id', 'desc')
            ->skip($start)->take($totalList)->get();

        if (count($workers) > 0) {
            foreach ($workers as $k => $v) {
                $v->age = date('Y', time()) - date('Y', strtotime($v->birthday));

                if ($v->sex == 1) {
                    $v->sex = '男';
                } elseif ($v->sex == 2) {
                    $v->sex = '女';
                }

                $v->jobarea = CollArea::getAreaName($v->jobarea1);

                if (trim($v->jobarea) == '') {
                    $v->jobarea = "地区不限";
                }

                $v->jobsort = CollPosition::where('cid', $v->jobsort1)->value('name');
            }
        }

        return response()->json(['status' => 1, 'data' => $workers]);
    }

    /**
     * 我的预约
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function appointJobs(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $jobsr = DB::table('resume_send as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            //获取字段
            ->select(
                't1.personal_uid', 't1.created_at',
                't2.id', 't2.job_title', 't2.job_category1', 't2.location1', 't2.address', 't2.salary', 't2.description', 't2.welfare', 't2.updatetime', 't2.job_status', 't2.begin_date',
                't3.company_name', 't3.logo'
            )
            ->where('t2.job_status', 5)
            ->where('t2.uid', $uid)
            ->orderBy('id', 'desc')
            ->skip($start)
            ->take(self::$totalList)
            ->get();

        if (count($jobsr) > 0) {
            foreach ($jobsr as $k => $v) {
                //地区
//                $v->location = CollArea::getAreaName($v->location1);
//
//                if (trim($v->location) == '') {
//                    $v->location = "地区不限";
//                }
//                if ($v->address) {
//                    $v->location = $v->location . ' ' . $v->address;
//                }
//
//                $v->job_category1 = CollPosition::getPosName($v->job_category1);

                $uinfo = Resume::where('uid', $v->personal_uid)->first();
                $v->headimg = $uinfo->avatar;
                $v->realname = $uinfo->realname;
                $v->sex = $uinfo->sex == 1 ? '男' : '女';
                $v->age = date('Y', time()) - date('Y', strtotime($uinfo->birthday));
                $v->work_year = $uinfo->work_year;
            }
        }

        $totalCount = DB::table('resume_send as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            //获取字段
            ->where('t2.job_status', 5)
            ->where('t2.uid', $uid)
            ->count();

        return response()->json(['status' => 1, 'data' => ['list' => $jobsr, 'totalCount' => $totalCount]]);
    }
}
